<template>
  <edit-dialog :centerDialogVisible="visible"  :tilte="title" :default-button="false"
      @Cancel="handlerCancel" @Submit="handlerSubmit" :width="width">
      <template #content>
        <layout-card ref="layoutCardRef" v-if="state == 1" :filters="applyStoreOptions" @search-change="searchChange" @search-reset="searchReset">
          <div class="table-common">
            <div class="goods">
              <div :class="applyStoreSelected.includes(item.taskId) ? 'goods_content_select' : 'goods_content'"
                 @click="handlerApplyStoreSelect(item)"
                v-for="(item, index) in tableData" :key="index">
                <img :src="item['goodsFiles'] ? item['goodsFiles'][0]['resourceAddress'] : image.noImg" class="image" />
                <div class="message">
                  <el-icon class="message-icon" size="28px"
                    :color="applyStoreSelected.includes(item.taskId) ? '#409EFF' : '#d6d4d4'">
                    <CircleCheckFilled />
                  </el-icon>
                  <div class="message_content">
                    <div class="type" :title="item['goodsName']">{{ item['goodsName']}}</div>
                    <div></div>
                  </div>
                  <div class="message_content">
                      <div class="headline">物品类型：</div>
                      <div class="headline_content">{{ getGoodsTypeName(item['goodsType']) }}</div>
                    </div>
                    <div class="message_content" >
                      <div class="headline">捡拾日期：</div>
                      <div class="headline_content">{{ dayjs(item['pickUpTime']).format('YYYY-MM-DD HH:mm:ss') }}</div>
                    </div>
                    <div class="message_content">
                      <div class="headline">捡拾地：</div>
                      <div class="headline_content pickUpPlace" :title="item['pickUpPlace']">{{ item['pickUpPlace'] }}</div>
                    </div>
                    <div class="message_content">
                      <div class="headline">物品编号：</div>
                      <div class="headline_content">{{ item['goodsCode'] }}</div>
                    </div>
                </div>
                <!-- <div
                  :class="applyStoreSelected.indexOf(item.taskId) != -1 ? 'gray_overdue_active' : 'gray_overdue'">
                  ✔
                </div> -->
              </div>
            </div>
          </div>
        </layout-card>
        <layout-card ref="layoutCardPickUp" v-else>
          <div class="table-common">
            <div class="goods">
              <div :class="applyStoreSelected.indexOf(item.taskId) != -1 ? 'goods_content_select' : 'goods_content'"
                @click="handlerApplyStoreSelect(item)"
                v-for="(item, index) in tableData" :key="index">
                <img :src="item['goodsFiles'] ? item['goodsFiles'][0]['resourceAddress'] : image.noImg" class="image" />
                <div class="message">
                  <div class="message_content">
                    <div class="type" :title="item['goodsName']">{{ item['goodsName'] }}</div>
                  </div>
                  <div class="message_content">
                      <div class="headline">物品类型：</div>
                      <div class="headline_content">{{ getGoodsTypeName(item['goodsType']) }}</div>
                    </div>
                    <div class="message_content" >
                      <div class="headline">捡拾日期：</div>
                      <div class="headline_content">{{ dayjs(item['pickUpTime']).format('YYYY-MM-DD HH:mm:ss') }}</div>
                    </div>
                    <div class="message_content" >
                      <div class="headline">捡拾地：</div>
                      <div class="headline_content pickUpPlace" :title="item['pickUpPlace']">{{ item['pickUpPlace'] }}</div>
                    </div>
                    <div class="message_content">
                      <div class="headline">物品编号：</div>
                      <div class="headline_content">{{ item['goodsCode'] }}</div>
                    </div>
                </div>
                <div
                  :class="applyStoreSelected.indexOf(item.taskId) != -1 ? 'gray_overdue_active' : 'gray_overdue'">
                  ✔
                </div>
              </div>
            </div>
          </div>
        </layout-card>
      </template>
      <template #custom>
        <span class="dialog-footer">
          <el-button @click="handlerCancel">取消</el-button>
          <el-button type="primary" @click="handlerSubmit(1)" v-if="state == 1" :disabled="applyStoreSelected.length === 0" :loading="loading">申请入库</el-button>
          <el-button type="primary" @click="handlerSubmit(2)" v-if="state == 2" :disabled="applyStoreSelected.length === 0" :loading="loading">接收</el-button>
        </span>
      </template>
    </edit-dialog>
</template>
<script lang="ts" setup>
import { ref, defineProps, computed, watch } from 'vue'
import type { FilterItem } from '@/components/FilterBar/types'
import { useStore } from 'vuex'
import LayoutCard from '@/components/LayoutCard/index.vue'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'
import { image } from '@/assets/index'
import { applyStoreOptions } from './config/filters'
import dayjs from 'dayjs'
import { getAllGoodsReg, acceptPickPuGoods, AcceptGoodsReq } from '@/api/lose/goodsReg'
import { getGoodsTypeName } from '@/utils/common'
const search = ref<any>({})
const title = ref('申请入库')
const width = ref('80%')
const loading = ref(false)
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  state: {
    type: Number,
    default: 1 // 申请入库,1、入库，2、批量接收
  }
})
const applyStoreSelected = ref<Array<string>>([])
const emit = defineEmits(['cancel', 'submit'])
const tableData = ref([])
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const layoutCardRef = ref()
const layoutCardPickUp = ref()
const needWarehouse = ref(true)
const handlerCancel = () => {
  tableData.value = []
  applyStoreSelected.value = []
  emit('cancel')
}
// 申请入库
const handlerSubmit = (state: number) => {
  if (applyStoreSelected.value.length === 0) {
    ElMessage.error('请选择物品')
    return
  }
  loading.value = true
  const swiValue = state === 1 ? '3' : '2'
  const tips = state === 1 ? '入库' : '接收'
  const params: Array<AcceptGoodsReq> = []
  applyStoreSelected.value.forEach(id => {
    const param = {
      taskId: id,
      content: {
        creator: {
          id: userInfo.value.userId,
          name: userInfo.value.name,
          organId: userInfo.value.organId,
          organName: userInfo.value.organName
        }
      },
      swi: swiValue
    }
    params.push(param)
  })
  acceptPickPuGoods(params).then((res: any) => {
    if (res?.code === '1') {
      ElMessage.success(tips + '成功！')
    } else {
      ElMessage.error(res?.message || tips + '失败，请重试！')
    }
    emit('submit')
    loading.value = false
  }).catch(err => {
    loading.value = false
    ElMessage.error(err.message || tips + '失败，请重试！')
  })
}

/**
 * 申请入库物品点击
 */
const handlerApplyStoreSelect = (item: any) => {
  if (applyStoreSelected.value.indexOf(item.taskId) !== -1) {
    applyStoreSelected.value.splice(applyStoreSelected.value.indexOf(item.taskId), 1)
  } else {
    applyStoreSelected.value.push(item.taskId)
  }
}

/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  search.value = data
  needWarehouse.value = false
  delete search.value.isDefaultWarehouse
  getData()
}

/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data: FilterDataType) => {
  search.value = data
  applyStoreSelected.value = []
  needWarehouse.value = false
  delete search.value.isDefaultWarehouse
  getData()
}
const getData = () => {
  search.value.taskProcess = '未接收'
  if (props.state === 1) { // 入库
    if (Array.isArray(search.value.storePosition)) {
      search.value.storePosition.length === 0 ? delete search.value.storePosition : search.value.storePosition = search.value.storePosition.join(',')
    }
    if (Array.isArray(search.value.storeTerminal)) {
      search.value.storeTerminal.length === 0 ? delete search.value.storeTerminal : search.value.storeTerminal = search.value.storeTerminal.join(',')
    }
    if (Array.isArray(search.value.storeTime)) {
      search.value.storeTime.length === 0 ? delete search.value.storeTime : search.value.storeTime = search.value.storeTime.join(',')
    }
    if (Array.isArray(search.value.goodsType)) {
      search.value.goodsType.length === 0 ? delete search.value.goodsType : search.value.goodsType = search.value.goodsType.join(',')
    }
    if (Array.isArray(search.value.startTime)) {
      if (search.value.startTime.length > 0) {
        const date = search.value.startTime
        search.value.startTime = date[0] + ' 00:00:00'
        search.value.endTime = date[1] + ' 23:59:59'
      } else {
        delete search.value.startTime
      }
    }
    search.value.taskProcess = '已接收'
    if (needWarehouse.value) {
      search.value.isDefaultWarehouse = 'Y'
    }
  }
  const params = {
    ...search.value
  }
  getAllGoodsReg(params).then(res => {
    if (res.data) {
      // @ts-ignore
      tableData.value = res.data
    }
  })
}
watch(() => props.visible, (newVal) => {
  if (newVal) {
    tableData.value = []
    loading.value = false
    applyStoreSelected.value = []
    needWarehouse.value = true
    title.value = '申请入库'
    if (props.state === 2) {
      title.value = '批量接收'
    }
    getData()
  }
})
watch(
  () => store.state.terminal.data, () => {
    const options: Array<any> = []
    store.state.terminal.data.forEach((ele: any) => {
      options.push(ele)
    })
    applyStoreOptions.value[4].inputProps.options = options
  }
)
watch(
  () => store.state.goodsType.typeList,
  () => {
    const options: Array<any> = []
    store.state.goodsType.typeList.forEach((ele: any) => {
      options.push({ label: ele.goodsType, value: ele.typeId })
    })
    applyStoreOptions.value[6].inputProps.options = options
  }
)
</script>
<style lang="less" scoped>

.table-common {
  width: 100%;
  background-color: #fff;
  .goods {
    max-height: 450px;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    .goods_content,
    .goods_content_select {
      // width: calc((1920px - 650px) / 3);
      width: calc(100% / 3 - 30px);
      height: 180px;
      background: #F3F4F7;
      border-radius: 8px;
      margin-top: 24px;
      margin-right: 24px;
      display: flex;
      align-items: center;
      position: relative;
      .image {
        width: 132px;
        height: 132px;
        border-radius: 10px;
        margin-left: 15px;
      }
      .message {
        margin-left: 15px;
        margin-top: 5px;
        width: 100%;
        .message-icon {
          position: absolute;
          top: 10px;
          right: 10px;

        }
        .message_content {
          display: flex;
          margin-top: 4px;
          .type {
            font-size: 16px;
            font-family: "HarmonyOS_Sans_SC_Bold",sans-serif;
            color: #535862;
            font-weight: bolder;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 40%;
          }
          .pickUpPlace {
            position: relative;
          }
          .type:hover::after,.pickUpPlace:hover::after {
            position: absolute;
            top: 100px;
            left: 10px;
            content: attr(data-title);
            // color:red;
            border: 1px solid #000;
            border-radius: 5px ;
            background-color: #333;
          }
          .terminal {
            margin-left: 16px;
            display: inline-block;
            text-align: center;
            width: 50px;
            height: 22px;
            line-height: 22px;
            background: rgb(0 148 255 / 12%);
            border-radius: 6px;
            border: 1px solid rgb(47 143 241 / 40%);
            font-size: 14px;
            color: #2F7DF1;
            ;
          }
          .headline {
            width: 70px;
            height: 22px;
            font-size: 14px;
            font-family: "HarmonyOS_Sans_SC",sans-serif;
            color: #989DAA;
            line-height: 22px;
          }
          .headline_content {
            height: 22px;
            font-size: 14px;
            font-family: "HarmonyOS_Sans_SC",sans-serif;
            color: #535862;
            line-height: 22px;
          }
        }
      }
    }
    .goods_content_select {
      background: #EBF2FA;
      border: 1px solid #327ECB;
    }
    .goods_content:hover,
    .goods_content_select:hover {
      cursor: pointer;
    }
    .hidden_overdue {
      display: none;
    }
    .gray_overdue,.gray_overdue_active {
      height: 22px;
      width: 24px;
      background: rgb(215 215 215);
      border-radius: 24px;
      text-align: center;
      border: 1px solid rgb(215 215 215 / 40%);
      font-size: 14px;
      font-family: "HarmonyOS_Sans_SC",sans-serif;
      color: #FFF;
      position: absolute;
      top: 5px;
      right: 8px;
    }
    .gray_overdue_active {
      background: rgb(51 126 202);
      border: 1px solid rgb(51 126 202 / 40%);
    }
    .green_overdue {
      height: 22px;
      background: rgb(255 179 31 / 12%);
      border-radius: 6px;
      border: 1px solid rgb(255 159 58 / 40%);
      font-size: 14px;
      font-family: "HarmonyOS_Sans_SC",sans-serif;
      color: #FF8F3A;
      line-height: 22px;
      padding-left: 8px;
      padding-right: 8px;
      position: absolute;
      top: 5px;
      right: 8px;
    }
  }
}
.buttonCancel {
  width: 88px;
}
.buttonReceive {
  width: 88px;
  color: #FFF;
  background: #337FCC;
  border-radius: 6px;
  border: 1px solid #337FCC;
}
</style>
